package com.atguigu.flink.chapter09;

import com.atguigu.flink.chapter05.Source.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.nfa.aftermatch.AfterMatchSkipStrategy;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/1/26 14:51
 */
public class Flink08_CEP_API {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .readTextFile("input/sensor-cep.txt")
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.valueOf(split[1]), Integer.valueOf(split[2]));
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forMonotonousTimestamps()
                                .withTimestampAssigner((element, ts) -> element.getTs() * 1000L)
                );

        // 模式组：类似sql里面的子查询，把整个模式序列当成一个整体，再去指定次数
        Pattern<WaterSensor, WaterSensor> pattern =
                Pattern
//                        .<WaterSensor>begin("start", AfterMatchSkipStrategy.noSkip()) // 默认的，不跳过
//                        .<WaterSensor>begin("start", AfterMatchSkipStrategy.skipToNext()) // 相同开头，只保留第一个
//                        .<WaterSensor>begin("start", AfterMatchSkipStrategy.skipPastLastEvent()) // 以sensor_1开头的，只保留第一个
//                        .<WaterSensor>begin("start", AfterMatchSkipStrategy.skipToFirst("start")) // 以指定事件为标准，在它之前的其他匹配，都抛弃
                        .<WaterSensor>begin("start", AfterMatchSkipStrategy.skipToLast("start")) // 以指定事件为标准，除了它的最后一个匹配，其他匹配，都抛弃
                        .where(new SimpleCondition<WaterSensor>() {
                            @Override
                            public boolean filter(WaterSensor value) throws Exception {
                                return "sensor_1".equals(value.getId());
                            }
                        })
                        .times(1,3)
                        .consecutive()
                        .next("next")
                        .where(new SimpleCondition<WaterSensor>() {
                            @Override
                            public boolean filter(WaterSensor value) throws Exception {
                                return "sensor_2".equals(value.getId());
                            }
                        });


        // 2.应用规则
        PatternStream<WaterSensor> sensorPS = CEP.pattern(sensorDS, pattern);

        // 3.获取匹配结果
        SingleOutputStreamOperator<String> resultDS = sensorPS.select(new PatternSelectFunction<WaterSensor, String>() {

            @Override
            public String select(Map<String, List<WaterSensor>> pattern) throws Exception {
                return pattern.toString();
            }
        });


        resultDS.print();


        env.execute();
    }
}
